<template>
  <div v-loading="isView" class="flow-containers" :class="{ 'view-mode': isView }">
    <el-container style="height: 100%">
      <el-header style="border-bottom: 1px solid rgb(218 218 218);height: auto;padding-left:0">
        <div style="display: flex; padding: 10px 0; justify-content: space-between;">
          <el-button-group>
            <el-upload action="" :before-upload="openBpmn" style="margin-right: 10px; display:inline-block;">
              <el-tooltip effect="dark" content="加载xml" placement="bottom">
                <el-button size="default" :icon="FolderOpened" aria-label="加载xml" />
              </el-tooltip>
            </el-upload>
            <el-tooltip effect="dark" content="新建" placement="bottom">
              <el-button size="default" :icon="Plus" aria-label="新建" @click="newDiagram" />
            </el-tooltip>
            <el-tooltip effect="dark" content="自适应屏幕" placement="bottom">
              <el-button size="default" :icon="Rank" aria-label="自适应屏幕" @click="fitViewport" />
            </el-tooltip>
            <el-tooltip effect="dark" content="放大" placement="bottom">
              <el-button size="default" :icon="ZoomIn" aria-label="放大" @click="zoomViewport(true)" />
            </el-tooltip>
            <el-tooltip effect="dark" content="缩小" placement="bottom">
              <el-button size="default" :icon="ZoomOut" aria-label="缩小" @click="zoomViewport(false)" />
            </el-tooltip>
            <el-tooltip effect="dark" content="后退" placement="bottom">
              <el-button size="default" :icon="Back" aria-label="后退" @click="modeler.value.get('commandStack').undo()" />
            </el-tooltip>
            <el-tooltip effect="dark" content="前进" placement="bottom">
              <el-button size="default" :icon="Right" aria-label="前进" @click="modeler.value.get('commandStack').redo()" />
            </el-tooltip>
<!--            <el-button size="default" icon="el-icon-share" @click="processSimulation">-->
<!--              {{ this.simulationStatus ? '退出模拟' : '开启模拟' }}-->
<!--            </el-button>-->
<!--            <el-button size="default" icon="el-icon-first-aid-kit" @click="handlerIntegrityCheck">-->
<!--              {{ this.bpmnlintStatus ? '关闭检查' : '开启检查' }}-->
<!--            </el-button>-->
          </el-button-group>
          <el-button-group>
            <el-button size="default" :icon="View" aria-label="查看xml" @click="showXML">查看xml</el-button>
            <el-button size="default" :icon="Download" aria-label="下载xml" @click="saveXML(true)">下载xml</el-button>
            <el-button size="default" :icon="Picture" aria-label="下载svg" @click="saveImg('svg', true)">下载svg</el-button>
            <el-button size="default" type="primary" aria-label="保存模型" @click="save">保存模型</el-button>
            <el-button size="default" type="danger" aria-label="关闭" @click="goBack">关闭</el-button>
          </el-button-group>
        </div>
      </el-header>
      <!-- 流程设计页面 -->
      <el-container style="align-items: stretch">
        <el-main>
          <div ref="canvas" class="canvas" />
        </el-main>

        <!--右侧属性栏-->
        <el-card shadow="never" class="normalPanel">
          <!-- <Designer :modelerStore="modelerStore" /> -->
          <Designer v-if="loadCanvas" />
        </el-card>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, getCurrentInstance } from 'vue'
import customTranslate from './customPanel/customTranslate'
import Modeler from 'bpmn-js/lib/Modeler'
import Designer from './designer'
import getInitStr from './flowable/init'
import { StrUtil } from '@/utils/StrUtil'
// 引入flowable的节点文件
import FlowableModule from './flowable/flowable.json'
import customControlsModule from './customPanel'
// 批量引入 Element Plus 图标
import { Plus, FolderOpened, Rank, ZoomIn, ZoomOut, Back, Right, View, Download, Picture } from '@element-plus/icons-vue'

// props
const props = defineProps({
  xml: { type: String, default: '' },
  isView: { type: Boolean, default: false }
})

// emits
const emit = defineEmits(['save', 'showXML'])

// 响应式数据
const modeler = ref(null)
const zoom = ref(1)
const loadCanvas = ref(false)
const simulationStatus = ref(false)
const bpmnlintStatus = ref(false)
const simulation = ref(true)
const designer = ref(true)

const { proxy } = getCurrentInstance();
const modelerStore = proxy.modelerStore;

// const modelerStore = ref({
//   modeler: null,
//   modeling: null,
//   moddle: null,
//   canvas: null,
//   bpmnFactory: null,
//   elRegistry: null
// })

// const additionalModules = computed(() => [
//   customControlsModule,
//   { translate: ['value', customTranslate] }
// ])

// 监听 xml 变化
watch(
  () => props.xml,
  (newVal) => {
    if (StrUtil.isNotBlank(newVal)) {
      createNewDiagram(newVal)
    } else {
      newDiagram()
    }
  },
  { immediate: true }
)

const additionalModules = computed(() => {
  const modules = [];
  modules.push(customControlsModule);
  modules.push({
    translate: ['value', customTranslate]
  });
  return modules;
});

onMounted(() => {
  // 创建bpmn 实例
  const m = new Modeler({
    container: canvas.value,
    additionalModules: additionalModules.value,
    moddleExtensions: { flowable: FlowableModule },
    keyboard: { bindTo: document }
  })
  modeler.value = m
  
  // 先设置modelerStore中的所有属性
  modelerStore.modeler = m
  modelerStore.modeling = m.get('modeling')
  modelerStore.moddle = m.get('moddle')
  modelerStore.canvas = m.get('canvas')
  modelerStore.bpmnFactory = m.get('bpmnFactory')
  modelerStore.elRegistry = m.get('elementRegistry')
  
  // 加载XML或创建新图
  if (StrUtil.isBlank(props.xml)) {
    newDiagram()
  } else {
    createNewDiagram(props.xml)
  }
})

const canvas = ref(null)

// 方法
function newDiagram() {
  createNewDiagram(getInitStr())
}

async function createNewDiagram(data) {
  if (StrUtil.isNotBlank(modelerStore.modeler)) {
    data = data.replace(/<!\[CDATA\[(.+?)]]>/g, (match, str) => str.replace(/</g, '&lt;'))
    try {
      await modelerStore.modeler.importXML(data)
      fitViewport()
    } catch (err) {
      console.error(err.message, err.warnings)
    }
  }
}

function fitViewport() {
  zoom.value = modelerStore.canvas.zoom('fit-viewport')
  const bbox = document.querySelector('.flow-containers .viewport').getBBox()
  const currentViewBox = modelerStore.canvas.viewbox()
  const elementMid = {
    x: bbox.x + bbox.width / 2 - 65,
    y: bbox.y + bbox.height / 2
  }
  modelerStore.canvas.viewbox({
    x: elementMid.x - currentViewBox.width / 2,
    y: elementMid.y - currentViewBox.height / 2,
    width: currentViewBox.width,
    height: currentViewBox.height
  })
  zoom.value = (bbox.width / currentViewBox.width) * 1.8
  loadCanvas.value = true
}

function zoomViewport(zoomIn = true) {
  zoom.value = modelerStore.canvas.zoom()
  zoom.value += zoomIn ? 0.1 : -0.1
  modelerStore.canvas.zoom(zoom.value)
}

function getProcess() {
  const element = getProcessElement()
  return {
    id: element.id,
    name: element.name,
    category: element.processCategory
  }
}

function getProcessElement() {
  const rootElements = modelerStore.modeler.getDefinitions().rootElements
  for (let i = 0; i < rootElements.length; i++) {
    if (rootElements[i].$type === 'bpmn:Process') return rootElements[i]
  }
}

async function saveXML(download = false) {
  try {
    const { xml } = await modelerStore.modeler.saveXML({ format: true })
    if (download) {
      downloadFile(`${getProcessElement().name}.bpmn20.xml`, xml, 'application/xml')
    }
    return xml
  } catch (err) {
    console.log(err)
  }
}

async function showXML() {
  try {
    const xmlStr = await saveXML()
    emit('showXML', xmlStr)
  } catch (err) {
    console.log(err)
  }
}

async function saveImg(type = 'svg', download = false) {
  try {
    const { svg } = await modelerStore.modeler.saveSVG({ format: true })
    if (download) {
      downloadFile(getProcessElement().name, svg, 'image/svg+xml')
    }
    return svg
  } catch (err) {
    console.log(err)
  }
}

async function save() {
  const process = getProcess()
  const xml = await saveXML()
  const svg = await saveImg()
  const result = { process, xml, svg }
  emit('save', result)
  window.parent.postMessage(result, '*')
  goBack()
}

function openBpmn(file) {
  const reader = new FileReader()
  reader.readAsText(file, 'utf-8')
  reader.onload = () => {
    createNewDiagram(reader.result)
  }
  return false
}

function downloadFile(filename, data, type) {
  const a = document.createElement('a')
  const url = window.URL.createObjectURL(new Blob([data], { type }))
  a.href = url
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(url)
}

function goBack() {
  const obj = { path: '/flowable/definition', query: { t: Date.now() } }
  // 这里需要根据你的全局tab实现方式调用关闭
  proxy.$tab.closeOpenPage(obj);
}
</script>

<style lang="scss">
/*左边工具栏以及编辑节点的样式*/
@import "bpmn-js/dist/assets/diagram-js.css";
@import "bpmn-js/dist/assets/bpmn-font/css/bpmn.css";
@import "bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css";
@import "bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css";
//@import "~bpmn-js-bpmnlint/dist/assets/css/bpmn-js-bpmnlint.css";
.view-mode {
  .el-header, .el-aside, .djs-palette, .bjs-powered-by {
    display: none;
  }
  .el-loading-mask {
    background-color: initial;
  }
  .el-loading-spinner {
    display: none;
  }
}

.flow-containers {
  width: 100%;
  height: 100%;
  .canvas {
    min-height: 850px;
    width: 100%;
    height: 100%;
    background: url("")
  }
  .panel {
    position: absolute;
    right: 0;
    top: 50px;
    width: 300px;
  }
  .load {
    margin-right: 10px;
  }
  .normalPanel {
    width: 460px;
    height: 100%;
    padding: 20px 20px;
  }

  .el-main {
    position: relative;
    padding: 0;
  }

  .el-main .button-group {
    display: flex;
    flex-direction: column;
    position: absolute;
    width: auto;
    height: auto;
    top: 10px;
    right: 10px;
  }

  .button-group .el-button {
    width: 100%;
    margin: 0 0 5px;
  }
}
</style>
